package com.tmall.tmall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tmall.tmall.mapper.UserMapper;
import com.tmall.tmall.pojo.PageRt;
import com.tmall.tmall.pojo.User;
import com.tmall.tmall.pojo.UserLogin;
import com.tmall.tmall.service.UserService;
import com.tmall.tmall.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public User login(UserLogin user) throws NoSuchAlgorithmException {
//        user.setPassword(MD5Utils.md5Encrypt(user.getPassword()));
        return userMapper.login(user);
    }

    @Override
    public User getByName(UserLogin userLogin){
        return userMapper.getByName(userLogin);
    }

    @Override
    public void insert(UserLogin userLogin) throws NoSuchAlgorithmException {
//        userLogin.setPassword(MD5Utils.md5Encrypt(userLogin.getPassword()));
        userMapper.insert(userLogin);
    }

    @Override
    public PageRt page(Integer pageNum, Integer pageSize, String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userMapper.page(name);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return new PageRt(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void update(User user) throws NoSuchAlgorithmException {
//        if(user.getPassword()!=null){
//            user.setPassword(MD5Utils.md5Encrypt(user.getPassword()));
//        }
        userMapper.update(user);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        //软删除，所以直接使用更新的方法
        for (Integer id : ids) {
            User user = User.builder().id(id).deleteAt(LocalDateTime.now()).build();
            userMapper.update(user);
        }
    }

    @Override
    public void updatePassword(Integer id, String oldPassword, String newPassword) throws NoSuchAlgorithmException {
        // 验证旧密码
//        String encryptedOldPassword = MD5Utils.md5Encrypt(oldPassword);
        User user = userMapper.checkPassword(id, oldPassword);
        if (user == null) {
            throw new RuntimeException("旧密码错误");
        }
        
        // 更新新密码
//        String encryptedNewPassword = MD5Utils.md5Encrypt(newPassword);
        userMapper.updatePassword(id, newPassword);
    }
}
